package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.LoginDAO;
import entity.Visitor;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub	 
		HttpSession session;
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String checkremember = request.getParameter("checkremember");
		
		System.out.println(" Servlet Login Say: " + userName);
		System.out.println(" Servlet Login Say: " + password);
	    	try {
	            Visitor visitor = new Visitor();
	            visitor.setUserName(userName);
	            visitor.setPassword(password);            
	            visitor = LoginDAO.checkVisistor(visitor);
	            
	            if(visitor.getId() != 0){
	                //request = ServletActionContext.getRequest();
	                session = request.getSession();
	                session.setAttribute("currentSession", visitor);
	                System.out.println(visitor.getUserName());
	                
	                if(checkremember != null && !checkremember.equals("")){
	                    Cookie c_u = new Cookie("c_u", visitor.getUserName());
	                    c_u.setMaxAge(300);
	                    response.addCookie(c_u);
	                }
	            	response.sendRedirect("Search.jsp");
	            }else {
	            	
         	        response.sendRedirect("login.jsp");
				}
	            
	    	} catch(Exception ex){
	    		response.sendRedirect("login.jsp");
	    	}
	}

}
